import 'package:demo/app/GenerateTestUserSig.dart';
import 'package:demo/app/modules/home/home_state.dart';
import 'package:demo/app/view/FloatingWindow.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:tencent_trtc_cloud/trtc_cloud.dart';
import 'package:tencent_trtc_cloud/trtc_cloud_def.dart';
import 'package:tencent_trtc_cloud/trtc_cloud_listener.dart';

class HomeController extends GetxController {
  HomeState state = HomeState();
  FloatingWindow floatVideoView = FloatingWindow();
  String remoteUser = '';

  Future<TRTCCloud?> initRemote() async {
    await createTrtc();
    return state.trtc;
  }

  Future<void> toggle() async {
    if (floatVideoView.isShowing) {
      await stopLocalPreview();
      floatVideoView.hide();
    }
  }

  Future<void> switchCamera() async {
    if (floatVideoView.isShowing) {
      state.isFrontCamera = !state.isFrontCamera;
      await stopLocalPreview();
      await startLocalPreview();
    }
  }

  Future createTrtc() async {
    if (state.trtc != null) return state.trtc;
    state.trtc?.setLogLevel(TRTCCloudDef.TRTC_LOG_LEVEL_NULL);
    if (await Permission.microphone.request() == PermissionStatus.granted &&
        await Permission.camera.request() == PermissionStatus.granted) {
      state.trtc = await TRTCCloud.sharedInstance();
      state.trtc?.registerListener(onRtcListener);
      return true;
    } else {
      return false;
    }
  }

  Future<void> startLocalPreview() async {
    await state.trtc?.startLocalPreview(state.isFrontCamera, state.localViewId);
    await state.trtc?.startLocalAudio(TRTCCloudDef.TRTC_AUDIO_QUALITY_DEFAULT);
  }

  Future<void> startRemotePreview() async {
    state.trtc?.startRemoteView(remoteUser,
        TRTCCloudDef.TRTC_VIDEO_STREAM_TYPE_BIG, state.remoteViewId);
  }

  @override
  void onClose() {
    super.onClose();
    if (floatVideoView.isShowing) {
      stopLocalPreview();
      floatVideoView.hide();
    }
    state.trtc?.exitRoom();
    state.trtc?.unRegisterListener(onRtcListener);
    TRTCCloud.destroySharedInstance();
  }

  void takePhoto() {}

  void setMute(bool isMute) {
    state.trtc?.muteLocalAudio(isMute);
    state.mute = !isMute;
    update(['mute']);
  }

  Future<void> enterRoom(String userId2) async {
    await createTrtc();
    floatVideoView.show();
    print("开始进入房间");
    await state.trtc?.enterRoom(
        TRTCParams(
            sdkAppId: GenerateTestUserSig.sdkAppId,
            userId: userId2,
            userSig: GenerateTestUserSig.genTestSig(userId2),
            role: TRTCCloudDef.TRTCRoleAnchor,
            roomId: 1230),
        TRTCCloudDef.TRTC_APP_SCENE_LIVE);
  }

  onRtcListener(type, param) async {
    print("onRtcListener${type} ${param}");
    if (type == TRTCCloudListener.onError) {
      if (param['errCode'] == -1308) {
        print('Failed to start screen recording');
      } else {
        print(param['errMsg']);
      }
    }
    if (type == TRTCCloudListener.onEnterRoom) {
      if (param > 0) {
        print('Enter room success');
      }
    }
    if (type == TRTCCloudListener.onExitRoom) {
      if (param > 0) {
        print('Exit room success');
      }
    }
    // Remote user entry
    if (type == TRTCCloudListener.onRemoteUserEnterRoom) {
      print("远程用户进入房间$param");
      remoteUser = param;
      state.showRemoteView = true;
      update();
    }
    // Remote user leaves room
    if (type == TRTCCloudListener.onRemoteUserLeaveRoom) {
      print('Remote user leaves room');
    }
    if (type == TRTCCloudListener.onUserVideoAvailable) {
      print("onUserVideoAvailable:${param['userId']},${param['available']}");
    }
  }

  stopLocalPreview() async {
    await state.trtc?.stopLocalPreview();
    await state.trtc?.stopLocalAudio();
  }
}
